<?php


namespace app\admin\order\logic;


use app\common\logic\BaseLogic;
use app\model\order\Order;
use app\model\order\OrderDeliveryPackage;
use app\model\order\OrderDetail;
use support\exception\BadException;
use support\utils\Time;

class OrderLogic extends BaseLogic
{
    /**
     * @var OrderDeliveryPackage
     */
    private OrderDeliveryPackage $deliveryPackage;

    public function __construct()
    {
        $this->model = new Order();
        $this->deliveryPackage = new OrderDeliveryPackage();
    }

    /**
     * 订单发货
     * @param $input
     */
    public function orderDelivery($input)
    {
        $needExpress = $input['type'] == 1;  // 1需要物流 2无需物流

        $order = $this->model->where(['id' => $input['order_id']])
            ->field([
                'id',
                'order_no',
            ])
            ->find();
        if ($needExpress) {
            $orderDetail = OrderDetail::where([
                'order_id' => $input['order_id'],
                'id' => $input['order_detail_ids'],
            ])
                ->field([
                    'id',
                    'num',
                    'delivery_status',
                    'goods_name',
                    'sku_name',
                ])
                ->select();


            $arr = [];
            foreach ($orderDetail as $value) {
                if ($value["delivery_status"] == OrderDetail::DELIVERY_STATUS_YES) {
                    throw new BadException("{$value['goods_name']}-{$value['sku_name']}已发货");
                }
                $arr[] = [
                    "order_detail_id" => $value['id'],
                    "num" => $value['num'],
                ];
            }
            $package = $this->deliveryPackage->where([
                "order_id" => $order['id'],
            ])
                ->field([
                    'package_no'
                ])
                ->order(["package_no" => "desc"])->find();
            $package_no = $package['package_no'] ?? 0;

            //创建发货包裹(需要物流)
            $this->deliveryPackage->insert([
                "delivery_no" => $input['delivery_no'],
                "delivery_time" => Time::now(),
                "delivery_goods_data" => json_encode($arr),
                "delivery_name" => $input['delivery_name'],
                "delivery_code" => $input['delivery_code'],
                "name" => "包裹" . $package_no + 1,
                "package_no" => $package_no + 1,
                "order_id" => $order['id'],
                "order_no" => $order['order_no'],
            ]);
        }


        if ($needExpress) {
            //标记订单详情发货状态
            OrderDetail::where([
                'order_id' => $input['order_id'],
                'id' => $input['order_detail_ids'],
                'delivery_status' => OrderDetail::DELIVERY_STATUS_NO,
            ])
                ->update([
                    'delivery_status' => OrderDetail::DELIVERY_STATUS_YES,
                    'delivery_time' => Time::now(),
                ]);
        } else {
            //标记订单详情发货状态
            OrderDetail::where([
                'order_id' => $input['order_id'],
                'id' => $input['order_detail_ids'],
                'delivery_status' => OrderDetail::DELIVERY_STATUS_NO,
            ])
                ->update([
                    'delivery_status' => OrderDetail::DELIVERY_STATUS_YES,
                    'delivery_time' => Time::now(),
                ]);
        }

        $unshippedCount = OrderDetail::where([
            ['order_id', '=', $input['order_id']],
            ['delivery_status', '=', OrderDetail::DELIVERY_STATUS_NO],
        ])
            ->count();
        $rows = $this->model->where([
            'id' => $input['order_id'],
            'status' => [Order::STATUS_WAIT_DELIVERY, Order::STATUS_SPLIT_DELIVERY]
        ])->update([
            'delivery_time' => Time::now(),
            'status' => $unshippedCount == 0 ? Order::STATUS_WAIT_TAKE_DELIVERY : Order::STATUS_SPLIT_DELIVERY
        ]);
        if (!$rows) {
            throw new BadException("发货失败");
        }
    }
}